<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\TaskQueueWaiting;
use AdminBundle\Task\TaskFactory;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Utility\Constant;

/**
 * Taskqueuewaiting controller.
 *
 * @Route("taskqueuewaiting")
 */
class TaskQueueWaitingController extends Controller
{
    /**
     * Lists all taskQueueWaiting entities.
     *
     * @Route("/", name="taskqueuewaiting_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $device_group = $request->get('device_group');
        if (!empty($date_range)) {
            $date_range = explode(" - ", $date_range);
            $starttime = $date_range[0];
            $endtime = $date_range[1];
        } else {
            $starttime = $endtime = null;
        }

        $starttime = date("Y-m-d", strtotime($starttime ?: "-3 day"));
        $endtime = date("Y-m-d", strtotime($endtime ?: "+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime,
            'device_group' => $device_group];

        $em = $this->getDoctrine()->getManager();
        $result = $em->getRepository('AdminBundle:TaskQueueWaiting')->pageQuery($params, $page);

        $baseGroup = $em->getRepository('AdminBundle:BaseGroup')->findAll();
        $params['baseGroups'] = $baseGroup;

        return $this->render('AdminBundle:taskqueuewaiting:index.html.twig', array_merge([
            'dataSources' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));
    }

    /**
     * Creates a new taskQueueWaiting entity.
     *
     * @Route("/new", name="taskqueuewaiting_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $taskQueueWaiting = new Taskqueuewaiting();
        $form = $this->createForm('AdminBundle\Form\TaskQueueWaitingType', $taskQueueWaiting, Constant::FORM_ATTR_CLASS);
        $form->handleRequest($request);

        if ($form->isSubmitted()) { // && $form->isValid()) {
            if (0) {
                $taskTemplate = $form->get('templateId')->getNormData();
                $baseGroup = $form->get('deviceGroupId')->getNormData();

//                $templateId = $taskTemplate->getViewData();
//                $deviceGroupId = $baseGroup->getViewData();
            } else {
                $taskTemplate = $form->getNormData()->getTemplateId();
                $baseGroup = $form->getNormData()->getDeviceGroupId();
//                $templateId = $taskTemplate->getId();
//                $deviceGroupId = $baseGroup->getId();
            }

            if ($taskTemplate == null || $baseGroup == null) {
                goto error_submit;
            }
            // 根据组取数据源
            $baseDataSource = $this->getDoctrine()->getManager()->getRepository('AdminBundle:BaseDataSource')
                ->findOneBy(['id' => $baseGroup->getDataSourceId()]);
            if ($baseDataSource == null) {
                goto error_submit;
            }
            $webchatUsername = $form->get('webchatUsername')->getViewData();
            $deviceId = $form->get('deviceId')->getViewData();//

            $taskQueueWaiting->setCtime(new \DateTime())
                ->setCreator($this->getUser()->getUsername())
                ->setIp($request->getClientIp())
                ->setAction($baseDataSource->getToken())
                ->setWebchatUsername($webchatUsername)
                ->setDeviceGroupId($baseGroup->getId())
                ->setDeviceId($deviceId)
                ->setName($taskTemplate->getName())
                ->setTemplateId($taskTemplate->getId())
                ->setUri($taskTemplate->getUri())
                ->setMethod($taskTemplate->getMethod());

            $count = $this->assign($taskQueueWaiting);

            return $this->redirectToRoute('taskqueuewaiting_index', ['count' => $count]);

            return $this->redirectToRoute('taskqueuewaiting_show', array('id' => $taskQueueWaiting->getId()));
        }

        error_submit:
        return $this->render('AdminBundle:taskqueuewaiting:new.html.twig', array(
            'taskQueueWaiting' => $taskQueueWaiting,
            'form' => $form->createView(),
        ));
    }

    private function assign(Taskqueuewaiting $taskQueueWaiting)
    {
        $em = $this->getDoctrine()->getManager();
        if (empty($taskQueueWaiting->getDeviceId())) {
            // 按终端组取设备
            $where = ['groupId' => $taskQueueWaiting->getDeviceGroupId()];
        } else {
            // 单一设备
            $where = ['id' => $taskQueueWaiting->getDeviceId()];
        }

        $baseDevices = $em->getRepository('AdminBundle:BaseDevice')->findBy($where);
        $count = 0;
        foreach ($baseDevices as $baseDevice) {
            $taskQueueWaiting->setDeviceId($baseDevice->getId())
                ->setDeviceName($baseDevice->getName() . ',' . $baseDevice->getImei());
            // 单一用户
            if (!empty($taskQueueWaiting->getWebchatUsername())) {
                $baseWebchatUsers = $em->getRepository('AdminBundle:BaseWebchatUser')->findBy(
                    ['deviceId' => $baseDevice->getId(),
                        'userName' => $taskQueueWaiting->getWebchatUsername()
                    ]);
            } else {
                // 多用户
                $baseWebchatUsers = $em->getRepository('AdminBundle:BaseWebchatUser')->findBy(['deviceId' => $baseDevice->getId()]);
            }

            foreach ($baseWebchatUsers as $baseWebchatUser) {
                $taskQueueWaiting->setMethod($baseWebchatUser->getId())
                    ->setNote($baseWebchatUser->getNickname())
                    ->setWebchatUsername($baseWebchatUser->getUserName());

                // 获取URI对应的返回结果
                $taskQueue = TaskFactory::create($taskQueueWaiting);
                $taskQueue->setDoctrineManager($em);
                $jsonTask = $taskQueue->jsonTask();

                if ($jsonTask == null) {
                    continue;
                }
                $clone_obj = clone $taskQueueWaiting;
                $clone_obj->setCtime(new \DateTime())
                    ->setParams($jsonTask);

                $em->persist($clone_obj);
                unset($clone_obj);
                $count++;
            }
            $em->flush();
        }
        return $count;
    }

    /**
     * Finds and displays a taskQueueWaiting entity.
     *
     * @Route("/{id}", name="taskqueuewaiting_show")
     * @Method("GET")
     */
    public
    function showAction(TaskQueueWaiting $taskQueueWaiting)
    {
        $deleteForm = $this->createDeleteForm($taskQueueWaiting);

        return $this->render('AdminBundle:taskqueuewaiting:show.html.twig', array(
            'dataSource' => $taskQueueWaiting,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing taskQueueWaiting entity.
     *
     * @Route("/{id}/edit", name="taskqueuewaiting_edit")
     * @Method({"GET", "POST"})
     */
    public
    function editAction(Request $request, TaskQueueWaiting $taskQueueWaiting)
    {
        $deleteForm = $this->createDeleteForm($taskQueueWaiting);
        $editForm = $this->createForm('AdminBundle\Form\TaskQueueWaitingType', $taskQueueWaiting, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('taskqueuewaiting_edit', array('id' => $taskQueueWaiting->getId()));
        }

        return $this->render('AdminBundle:taskqueuewaiting:edit.html.twig', array(
            'taskQueueWaiting' => $taskQueueWaiting,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a taskQueueWaiting entity.
     *
     * @Route("/{id}", name="taskqueuewaiting_delete")
     * @Method("DELETE")
     */
    public
    function deleteAction(Request $request, TaskQueueWaiting $taskQueueWaiting)
    {
        $form = $this->createDeleteForm($taskQueueWaiting);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($taskQueueWaiting);
            $em->flush();
        }

        return $this->redirectToRoute('taskqueuewaiting_index');
    }

    /**
     * Creates a form to delete a taskQueueWaiting entity.
     *
     * @param TaskQueueWaiting $taskQueueWaiting The taskQueueWaiting entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private
    function createDeleteForm(TaskQueueWaiting $taskQueueWaiting)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('taskqueuewaiting_delete', array('id' => $taskQueueWaiting->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
